﻿using System.Globalization;
using System.Windows.Data;

namespace Koala.Pro.Helpers
{
    public class DateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return null;
            }
            if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
                return System.Convert.ChangeType(value, targetType);
            }
            if (!DateTime.TryParse(value.ToString(), out var _))
            {
                return DBNull.Value;
            }
            return System.Convert.ChangeType(value, targetType);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return null;
            }
            if (!(value is string) && targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
                return System.Convert.ChangeType(value, targetType);
            }
            if (!DateTime.TryParse(value.ToString(), out var result))
            {
                return DBNull.Value;
            }
            return result;
        }
    }

}
